package com.phb.puhuibao.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.idp.pub.context.AppContext;
import com.idp.pub.dao.IBaseDao;
import com.idp.pub.dao.IPagerDao;
import com.idp.pub.service.impl.DefaultBaseService;
import com.phb.puhuibao.entity.MobileUser;
import com.phb.puhuibao.entity.UserAccount;
import com.phb.puhuibao.entity.UserAccountLog;
import com.phb.puhuibao.entity.UserLoan;
import com.phb.puhuibao.service.UserAccountService;

@Transactional
@Service("userAccountService")
public class UserAccountServiceImpl extends DefaultBaseService<UserAccount, String> implements UserAccountService {
	@javax.annotation.Resource(name = "appContext")
	private AppContext appContext;

	@javax.annotation.Resource(name = "userAccountDao")
	public void setBaseDao(IBaseDao<UserAccount, String> baseDao) {
		super.setBaseDao(baseDao);
	}

	@javax.annotation.Resource(name = "userAccountDao")
	public void setPagerDao(IPagerDao<UserAccount> pagerDao) {
		super.setPagerDao(pagerDao);
	}
	
	@javax.annotation.Resource(name = "mobileUserDao")
	private IBaseDao<MobileUser, String> mobileUserDao;	
	@javax.annotation.Resource(name = "userAccountLogDao")
	private IBaseDao<UserAccountLog, String> userAccountLogDao;
	@javax.annotation.Resource(name = "jdbcTemplate")
	private JdbcTemplate jdbcTemplate;


	@Override
	public void confirm(UserAccount entity) {
		// TODO Auto-generated method stub
			if (entity.getIsPaid() == 1) {
				String sql = "select 1 from phb_mobile_user where user_id=" + entity.getUserId() + " for update";
				this.jdbcTemplate.execute(sql);
				MobileUser u = mobileUserDao.get("" + entity.getUserId());				

				UserAccountLog log = new UserAccountLog();
				log.setUserId(entity.getUserId());

				if (entity.getProcessType() == 2) {
						u.setUserMoney(u.getUserMoney() + entity.getAmount());
						log.setBalanceAmount(this.getBalanceAmount(u) + entity.getAmount());
						log.setAmount(+ entity.getAmount());
						log.setChangeType("收入");
						log.setChangeDesc(entity.getUserNote());
						log.setAccountType(2);
				}else  if(entity.getProcessType() == 1){
						u.setUserMoney(u.getUserMoney() - entity.getAmount());
						u.setFrozenMoney(u.getFrozenMoney() - entity.getAmount());
	
						log.setBalanceAmount(this.getBalanceAmount(u) - u.getFrozenMoney());
						log.setAmount(- entity.getAmount());
						log.setChangeType("提现完成");
						log.setChangeDesc(entity.getUserNote());
						log.setAccountType(1);
				}			

				userAccountLogDao.save(log);
				mobileUserDao.update(u);
			}
			this.update(entity);
		}

	@Override
	public UserAccount processSave(UserAccount entity) {
		// TODO Auto-generated method stub
		if (entity.getProcessType() == 1) {
			String sql = "select 1 from phb_mobile_user where m_user_id=" + entity.getUserId() + " for update";
			this.jdbcTemplate.execute(sql);
			MobileUser u = mobileUserDao.get("" + entity.getUserId());			
			mobileUserDao.update(u);			
			UserAccountLog log = new UserAccountLog();
			log.setUserId(entity.getUserId());
			log.setAmount(entity.getAmount());
			log.setBalanceAmount(this.getBalanceAmount(u)-entity.getAmount());
			log.setChangeType("提现");
			log.setChangeDesc(entity.getUserNote());
			log.setAccountType(1);//0:支付 1:提现 2：收入
			userAccountLogDao.save(log);
		}
	
			save(entity);
		return entity;
	}

	@Override
	public int processDelete(int accountId) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public void refund(String orderId) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void adminCreate(UserAccount entity) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void processRefund(UserAccount entity, int accountType) {
		// TODO Auto-generated method stub
		
	}
    public double getBalanceAmount(MobileUser user){   	
    	Map<String , Object> params = new HashMap<String , Object>();
    	params.put("userId", user.getUserId());
    	params.put("orderBy", "paid_time");
    	params.put("order", "desc");
    	List<UserAccountLog> list = userAccountLogDao.find(params);   
    	double	balanceAmount=0.00;
    	if(list.size()>0){
    		balanceAmount = list.get(0).getBalanceAmount();
    	}
    	return balanceAmount;
    }
	/*@javax.annotation.Resource(name = "mobileUserDao")
	IBaseDao<MobileUser, String> mobileUserDao;
	public void confirm(UserAccount entity) {
		if (entity.getIsPaid() == 1) {
			String sql = "select 1 from phb_mobile_user where m_user_id=" + entity.getUserId() + " for update";
			this.jdbcTemplate.execute(sql);
			MobileUser u = mobileUserDao.get("" + entity.getUserId());
			MobileUser user = new MobileUser();
			user.setUserId(entity.getUserId());

			UserAccountLog log = new UserAccountLog();
			log.setUserId(entity.getUserId());

			if (entity.getProcessType() == 0) {
				user.setUserMoney(u.getUserMoney() + entity.getAmount());
				log.setBalanceAmount(user.getUserMoney() - u.getFrozenMoney());
				log.setAmount(+ entity.getAmount());
				log.setChangeType("鍏呭�煎畬鎴�");
			} else {
//				Map<String, Object> params = new HashMap<String, Object>();
//				params.put("UserId", entity.getUserId());
//				params.put("type", 0);
//				params.put("status", 1);
//				List<UserLoan> loans = baseUserLoanDao.find(params);
//				if (loans.size() > 0) {
//					for (UserLoan loan : loans) {
//						UserLoan l = new UserLoan();
//						l.setLoanId(loan.getLoanId());
//						l.setStatus(2);
//						baseUserLoanDao.update(l);
//					}
//					user.setFrozenMoney(u.getFrozenMoney());
//				} else {
					user.setUserMoney(u.getUserMoney() - entity.getAmount());
					user.setFrozenMoney(u.getFrozenMoney() - entity.getAmount());
//				}
				log.setBalanceAmount(user.getUserMoney() - user.getFrozenMoney());
				log.setAmount(- entity.getAmount());
				log.setChangeType("鎻愮幇瀹屾垚");
			}
			log.setChangeDesc(entity.getUserNote());
			log.setAccountType(0);

//			UserAccount userAccount = new UserAccount();
//			userAccount.setAccountId(entity.getAccountId());
//			userAccount.setIsPaid(1);
//			update(userAccount);
			
			userAccountLogDao.save(log);
			mobileUserDao.update(user);
		}
		this.update(entity);
	}

	public UserAccount processSave(UserAccount entity) {
		if (entity.getProcessType() == 1) {
			String sql = "select 1 from phb_mobile_user where m_user_id=" + entity.getUserId() + " for update";
			this.jdbcTemplate.execute(sql);
			MobileUser u = mobileUserDao.get("" + entity.getUserId());
			MobileUser user = new MobileUser();
			user.setUserId(entity.getUserId());
			//user.setUserMoney(u.getUserMoney());
//			Map<String, Object> params = new HashMap<String, Object>();
//			params.put("UserId", entity.getUserId());
//			params.put("type", 0);
//			params.put("status", 1);
//			UserLoan loan = baseUserLoanDao.unique(params);
//			if (loan == null) {
				user.setFrozenMoney(u.getFrozenMoney() + entity.getAmount());
//			} else {
//				user.setFrozenMoney(u.getFrozenMoney());
//			}
			mobileUserDao.update(user);
			
			UserAccountLog log = new UserAccountLog();
			log.setUserId(entity.getUserId());
			log.setAmount(entity.getAmount());
			log.setBalanceAmount(u.getUserMoney() - user.getFrozenMoney());
			log.setChangeType("鎻愮幇鍐荤粨");
			log.setChangeDesc(entity.getUserNote());
			log.setAccountType(0);
			userAccountLogDao.save(log);
		}
		
		// amount=999999999 鍙互鎹曟崏鍒癉ataIntegrityViolationException
		// amount=99999999  鎹曟崏涓嶅埌MysqlDataTruncation
//		try {
			save(entity);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
		
		if (appContext.getPayOnline() == 1) {
//			// 閾惰鎺ュ彛
//			if (entity.getProcessType() == 1) {
//				Map<String, Object> params = new HashMap<String, Object>();
//				params.put("UserId", entity.getUserId());
//				UserCard card = baseUserCardDao.unique(params);
//				Map<String, Object> data = withdraw(card.getBankPhone(), entity.getAmount(), card.getBankAccount().substring(0, 5), card.getBankAccount().substring(card.getBankAccount().length() - 4));
//				if ((int) data.get("status") == 1) {
//					String orderId = (String) data.get("result");
//					entity.setOrderId(orderId);
//				}
//			}
			if (entity.getProcessType() == 0) {
				entity.setIsPaid(1);
				confirm(entity);
			}
		}
		return entity;
	}

	public int processDelete(int accountId) {
		UserAccount entity = this.getBaseDao().get("" + accountId);
		if (entity.getProcessType() == 1) {
			String sql = "select 1 from phb_mobile_user where m_user_id=" + entity.getUserId() + " for update";
			this.jdbcTemplate.execute(sql);
			MobileUser u = mobileUserDao.get("" + entity.getUserId());
			MobileUser user = new MobileUser();
			user.setUserId(entity.getUserId());
			//user.setUserMoney(u.getUserMoney());
			user.setFrozenMoney(u.getFrozenMoney() - entity.getAmount());
			mobileUserDao.update(user);

			UserAccountLog log = new UserAccountLog();
			log.setUserId(entity.getUserId());
			log.setAmount(0.0);
			log.setBalanceAmount(u.getUserMoney() - user.getFrozenMoney());
			log.setChangeType("鎻愮幇鍙栨秷");
			log.setChangeDesc(entity.getUserNote());
			log.setAccountType(0);
			userAccountLogDao.save(log);
		}
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("accountId", accountId);
		int count = delete(params);
		return count;
	}

	@Override
	public void refund(String orderId) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("orderId", orderId);
		UserAccount entity = this.getBaseDao().unique(params);

		String sql = "select 1 from phb_mobile_user where m_user_id=" + entity.getUserId() + " for update";
		this.jdbcTemplate.execute(sql);
		MobileUser u = mobileUserDao.get("" + entity.getUserId());
		MobileUser user = new MobileUser();
		user.setUserId(entity.getUserId());
		user.setUserMoney(u.getUserMoney() - entity.getAmount());
		mobileUserDao.update(user);
		
		UserAccountLog log = new UserAccountLog();
		log.setUserId(entity.getUserId());
		log.setAmount(- entity.getAmount());
		log.setBalanceAmount(u.getUserMoney() - u.getFrozenMoney());
		log.setChangeType("閫�娆惧畬鎴愶紝绛夊緟閾惰鍏ヨ处");
		log.setChangeDesc(entity.getUserNote());
		log.setAccountType(0);
		userAccountLogDao.save(log);
		
		UserAccount account = new UserAccount();
		account.setAccountId(entity.getAccountId());
		account.setIsPaid(2);
		this.update(account);
	}

	*//**
	 * 鐢宠
	 *//*
	public void adminCreate(UserAccount entity) {
		String sql = "select 1 from phb_mobile_user where m_user_id=" + entity.getUserId() + " for update";
		this.jdbcTemplate.execute(sql);
		MobileUser u = mobileUserDao.get("" + entity.getUserId());
		MobileUser user = new MobileUser();
		user.setUserId(entity.getUserId());

		UserAccountLog log = new UserAccountLog();
		log.setUserId(entity.getUserId());

		if (entity.getProcessType() == 0) {
			user.setUserMoney(u.getUserMoney() + entity.getAmount());
			log.setBalanceAmount(user.getUserMoney() - u.getFrozenMoney());
			log.setAmount(entity.getAmount());
			log.setChangeType("鍏呭�煎畬鎴�");
		} else {
			user.setUserMoney(u.getUserMoney() - entity.getAmount());
			log.setBalanceAmount(user.getUserMoney() - u.getFrozenMoney());
			log.setAmount(- entity.getAmount());
			log.setChangeType("鎻愮幇瀹屾垚");
		}
		log.setChangeDesc(entity.getUserNote());
		log.setAccountType(0);

		userAccountLogDao.save(log);
		mobileUserDao.update(user);

		this.save(entity);
		UserAccount account = new UserAccount();
		account.setAccountId(entity.getAccountId());
		account.setIsPaid(entity.getIsPaid());
		account.setAdminNote(entity.getAdminNote());
		this.update(account);
	}

	
	// 鏀粯瀹濆拰寰俊鐨勬敮浠�   涓嶆秹鍙婂埌浣欓鍙樺姩
	private void confirmPay(UserAccount entity, int accountType) {
		MobileUser u = mobileUserDao.get("" + entity.getUserId());
		UserAccountLog log = new UserAccountLog();
		log.setUserId(entity.getUserId());
		log.setBalanceAmount(u.getUserMoney() - u.getFrozenMoney());  // 寰俊鏀粯 鍙秹鍙婂埌绗笁鏂逛綑棰濆彉鍔�,鏈� app 浣欓涓嶅彉鍔�
		log.setAmount(entity.getAmount());
		if (accountType == 32) {
			log.setChangeType("鏀粯瀹濇敮浠�");
		} else if (accountType == 33) {
			log.setChangeType("寰俊鏀粯");
		} else {
			log.setChangeType("鍏朵粬鏀粯");
		}
		log.setChangeDesc(entity.getUserNote());
		log.setAccountType(accountType);
		userAccountLogDao.save(log);
 
	}

	

	public void processRefund(UserAccount entity, int accountType) {
		save(entity);

		MobileUser u = mobileUserDao.get("" + entity.getUserId());
		MobileUser user = new MobileUser();
		user.setUserId(entity.getUserId());
		
		UserAccountLog log = new UserAccountLog();
		log.setUserId(entity.getUserId());
		if (accountType == 32) {
			log.setChangeType("鏀粯瀹濋��娆�");
			log.setBalanceAmount(u.getUserMoney()  - u.getFrozenMoney() );
		} else if (accountType == 33) {
			log.setChangeType("寰俊閫�娆�");
			log.setBalanceAmount(u.getUserMoney()  - u.getFrozenMoney() );
		} else {
			user.setUserMoney(u.getUserMoney() + entity.getAmount()); // 浣欓閫�娆�,鍔犲洖浣欓
			mobileUserDao.update(user);
			log.setChangeType("鍏朵粬閫�娆�");
			log.setBalanceAmount(u.getUserMoney()  - u.getFrozenMoney() +  entity.getAmount());
		}
		
		log.setAmount(entity.getAmount());
		log.setChangeDesc(entity.getUserNote());
		log.setAccountType(accountType);
		userAccountLogDao.save(log);
		

	}*/
}
